import format from "date-fns/format";
import addSeconds from "date-fns/addSeconds";
const TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

/**
 * 在某个时刻运行回调函数
 */
class RunOnTime {
  constructor() {
    this.stacks = {};

    // 定时器
    const counter = 0;
    setInterval(() => {
      const time = format(Date.now(), TIME_FORMAT);
      if (this.stacks[time]) {
        console.log("%c RunOnTime", "background:green;color:white", time);
        this.stacks[time]({ counter, time });
      }
    }, 1000);

    this.add = this.add.bind(this);
  }

  /**
   * 添加到执行队列
   * @param {Array, Number, Date } times - 执行时间
   * @param {Function} callback - 回调函数
   * @param {Number, Optional} delay=0 - 延迟执行
   */
  add({ times, callback, delay = 0 }) {
    if (!Array.isArray(times)) {
      times = [times];
    }
    times.forEach((time) => {
      const key = format(addSeconds(time, delay), TIME_FORMAT);
      this.stacks[key] = callback;
    });
  }
}

export default new RunOnTime();
